import * as Vue from 'vue'
import { defineStore } from 'pinia'
import { ApplyModule } from '@/services/modules/apply'
import * as httpService from '@/services/apply.service'
export const useUserStore = defineStore('user', () => {
  const aId = Vue.ref<string>()
  const authToken = Vue.ref<string | undefined>()
  const authInfo = Vue.ref<ApplyModule.UserAuthInfo | undefined>()
  // 获取用户信息的函数
  async function getAccountInfo() {
    const result = await httpService.getCurrentAuthInfo()
    authInfo.value = result.data;
  }

  async function getAdminAccountInfo() {
    const result = await httpService.getAdminAccountInfo()
    authInfo.value = result.data;
  }
  
  function setAuthToken(token: string) {
    authToken.value = token
    localStorage.setItem(getAuthTokenKey(), token) // 存储到 localStorage
  }

  function setOpCode(opCode: string) {
    if (!authInfo.value) {
      return;
    }
    authInfo.value.opCode = opCode;
  }

  function getAuthToken() {
    return localStorage.getItem(getAuthTokenKey()) || undefined
  }

  function getAuthTokenKey() {
    let key = "authToken";
    const isAdmin = window.location.href.includes('/admin') || window.location.href.includes('/login')
    if (isAdmin) {
      key = "authTokenAdmin"
    }
    return key;
  }

  function clearAuthToken() {
    authInfo.value = undefined
    authToken.value = undefined
    localStorage.removeItem(getAuthTokenKey()) // 退出登录时清除 token
  }

  async function userLogin(form:{ mobile: string, password: string}) {
    const res = await httpService.userLogin(form)
    authInfo.value = res.data;
    setAuthToken(res.data.authToken);
  }

  /**
   * 管理员登录函数
   * @param form - 包含手机号和密码的登录表单对象
   * @param form.mobile - 用户的手机号
   * @param form.password - 用户的密码
   * 该函数通过调用 httpService.userLogin 方法发送登录请求，
   * 成功后将响应数据中的 authInfo 和 authToken 分别设置到 authInfo.value 和通过 setAuthToken 方法设置的认证令牌中。
   */
  async function adminLogin(form:{ username: string, password: string}) {
    const res = await httpService.adminLogin(form)
    authInfo.value = res.data;
    setAuthToken(res.data.authToken);
  }

  async function userLogout() {
    clearAuthToken();
    
  }

  return {
    aId,
    authInfo,
    getAuthToken,
    getAccountInfo,
    setAuthToken,
    clearAuthToken,
    getAdminAccountInfo,
    userLogin,
    userLogout,
    adminLogin,
    setOpCode,
  }
})
